oseda_cli/
config.rs

1use std::error::Error;
2use std::fs::File;
3use std::io::BufWriter;
4use std::str::FromStr;
5use std::{ffi::OsString, fs};
6
7use chrono::{DateTime, Utc};
8use inquire::validator::Validation;
9use serde::{Deserialize, Serialize};
10use strum::IntoEnumIterator;
11
12use crate::cmd::check::OsedaCheckError;
13use crate::cmd::init::InitOptions;
14use crate::color::Color;
15use crate::github;
16use crate::tags::Tag;
17
18pub fn read_config_file<P: AsRef<std::path::Path>>(
19    path: P,
20) -> Result<OsedaConfig, OsedaCheckError> {
21    let config_str = fs::read_to_string(path.as_ref()).map_err(|_| {
22        OsedaCheckError::MissingConfig(format!(
23            "Could not find config file in {}",
24            path.as_ref().display()
25        ))
26    })?;
27
28    let conf: OsedaConfig = serde_json::from_str(&config_str)
29        .map_err(|_| OsedaCheckError::BadConfig("Could not parse oseda config file".to_owned()))?;
30
31    Ok(conf)
32}
33
34/// Reads and validates an oseda-config.json file in the working directory
35///
36/// This checks a few things:
37/// - the file exists and parses correctly
38/// - the git `user.name` matches the config author (unless --skip-git is passed)
39/// - the config `title` matches the name of the working directory
40///
41/// # Arguments
42/// * `skip_git` - skips the git author validation, primarily used for CI, not by the end user hopefully lol
43///
44/// # Returns
45/// * `Ok(OsedaConfig)` if the file is valid and all checks pass
46/// * `Err(OsedaCheckError)` if any check fails
47pub fn read_and_validate_config() -> Result<OsedaConfig, OsedaCheckError> {
48    let path = std::env::current_dir().map_err(|_| {
49        OsedaCheckError::DirectoryNameMismatch("Could not get path of working directory".to_owned())
50    })?;
51
52    let config_path = path.join("oseda-config.json");
53
54    let conf = read_config_file(config_path)?;
55
56    let in_ci = std::env::var("GITHUB_ACTIONS").is_ok_and(|v| v == "true");
57    let skip_git = in_ci;
58
59    validate_config(&conf, &path, skip_git, || {
60        github::get_config_from_user_git("user.name")
61    })?;
62
63    Ok(conf)
64}
65
66pub fn validate_config(
67    conf: &OsedaConfig,
68    current_dir: &std::path::Path,
69    skip_git: bool,
70    // very cool pass in a lambda, swap that lambda out in the tests
71    // https://danielbunte.medium.com/a-guide-to-testing-and-mocking-in-rust-a73d022b4075
72    get_git_user: impl Fn() -> Option<String>,
73) -> Result<(), OsedaCheckError> {
74    if !skip_git {
75        let gh_name = get_git_user().ok_or_else(|| {
76            OsedaCheckError::BadGitCredentials(
77                "Could not get git user.name from git config".to_owned(),
78            )
79        })?;
80
81        if gh_name != conf.author {
82            return Err(OsedaCheckError::BadGitCredentials(
83                "Config author does not match git credentials".to_owned(),
84            ));
85        }
86    }
87
88    let cwd = current_dir.file_name().ok_or_else(|| {
89        OsedaCheckError::DirectoryNameMismatch("Could not resolve path name".to_owned())
90    })?;
91
92    if cwd != OsString::from(conf.title.clone()) {
93        return Err(OsedaCheckError::DirectoryNameMismatch(
94            "Config title does not match directory name".to_owned(),
95        ));
96    }
97
98    Ok(())
99}
100
101/// Structure for an oseda-config.json
102#[derive(Serialize, Deserialize)]
103pub struct OsedaConfig {
104    pub title: String,
105    pub author: String,
106    pub tags: Vec<Tag>,
107    // effectively mutable. Will get updated on each deployment
108    pub last_updated: DateTime<Utc>,
109    pub color: String,
110}
111
112pub fn prompt_for_title() -> Result<String, Box<dyn Error>> {
113    let validator = |input: &str| {
114        if input.chars().count() < 2 {
115            Ok(Validation::Invalid(
116                ("Title must be longer than two characters").into(),
117            ))
118        } else {
119            Ok(Validation::Valid)
120        }
121    };
122
123    Ok(inquire::Text::new("Title: ")
124        .with_validator(validator)
125        .prompt()?)
126}
127/// Prompts the user for everything needed to generate a new OsedaConfig
128///
129/// # Returns
130/// * `Ok(OsedaConfig)` containing validated project config options
131/// * `Err` if a required input conf is invalid
132pub fn create_conf(options: InitOptions) -> Result<OsedaConfig, Box<dyn Error>> {
133    let title = match options.title {
134        Some(arg_title) => arg_title,
135        None => prompt_for_title()?.replace(" ", "-"),
136    };
137
138    let tags = match options.tags {
139        Some(arg_tags) => {
140            arg_tags
141                .iter()
142                .map(|arg_tag| Tag::from_str(arg_tag))
143                .collect::<Result<Vec<Tag>, _>>()
144                .map_err(|_| "Invalid tag. Custom Tags may be added to the oseda-config.json after initialization".to_string())?
145        },
146        None => prompt_for_tags()?
147    };
148
149    let color = match options.color {
150        Some(arg_color) => Color::from_str(&arg_color)
151            .map_err(|_| "Invalid color. Please use traditional english color names".to_string())?,
152        None => prompt_for_color()?,
153    };
154
155    let user_name = github::get_config_from_user_git("user.name")
156        .ok_or("Could not get github username. Please ensure you are signed into github")?;
157
158    Ok(OsedaConfig {
159        title: title.trim().to_owned(),
160        author: user_name,
161        tags,
162        last_updated: get_time(),
163        color: color.into_hex(),
164    })
165}
166
167/// Prompts user for categories associated with their Oseda project
168///
169/// # Returns
170/// * `Ok(Vec<Category>)` with selected categories
171/// * `Err` if the prompting went wrong somewhere
172fn prompt_for_tags() -> Result<Vec<Tag>, Box<dyn Error>> {
173    let options: Vec<Tag> = Tag::iter().collect();
174
175    let selected_tags =
176        inquire::MultiSelect::new("Select categories (type to search):", options.clone())
177            .prompt()?;
178
179    println!("You selected:");
180    for tags in selected_tags.iter() {
181        println!("- {:?}", tags);
182    }
183
184    Ok(selected_tags)
185}
186
187fn prompt_for_color() -> Result<Color, Box<dyn Error>> {
188    let options: Vec<Color> = Color::iter().collect();
189
190    let selected_color = inquire::Select::new(
191        "Select the color for your course (type to search):",
192        options.clone(),
193    )
194    .prompt()?;
195
196    println!("You selected: {:?}", selected_color);
197
198    Ok(selected_color)
199}
200
201/// Updates the configs last-updated
202/// Currently this is used on creation only, TODO fix this
203///
204/// # Arguments
205/// * `conf` - a previously loaded or generated OsedaConfig
206///
207/// # Returns
208/// * `Ok(())` if the file is successfully updated
209/// * `Err` if file writing fails
210pub fn update_time(mut conf: OsedaConfig) -> Result<(), Box<dyn Error>> {
211    conf.last_updated = get_time();
212
213    write_config(".", &conf)?;
214    Ok(())
215}
216
217/// Gets the current system time in UTC
218///
219/// # Returns
220/// * a `DateTime<Utc>` representing the current time
221fn get_time() -> DateTime<Utc> {
222    chrono::offset::Utc::now()
223}
224
225/// Write an OsedaConfig to the provided directory
226///
227/// # Arguments
228/// * `path` - the directory path to write into
229/// * `conf` - the `OsedaConfig` instance to serialize via serde
230///
231/// # Returns            color: Color::Black
232/// * `Ok(())` if the file is written successfully
233/// * `Err` if file creation or serialization fails
234pub fn write_config(path: &str, conf: &OsedaConfig) -> Result<(), Box<dyn Error>> {
235    let file = File::create(format!("{}/oseda-config.json", path))?;
236    let writer = BufWriter::new(file);
237
238    serde_json::to_writer_pretty(writer, &conf)?;
239
240    Ok(())
241}
242
243#[cfg(test)]
244mod test {
245    use std::path::Path;
246    use tempfile::tempdir;
247
248    use super::*;
249
250    #[allow(dead_code)]
251    fn mock_config_json() -> String {
252        r#"
253           {
254               "title": "TestableRust",
255               "author": "JaneDoe",
256               "category": ["ComputerScience"],
257               "last_updated": "2024-07-10T12:34:56Z"
258           }
259           "#
260        .trim()
261        .to_string()
262    }
263
264    #[test]
265    fn test_read_config_file_missing() {
266        let dir = tempdir().unwrap();
267        let config_path = dir.path().join("oseda-config.json");
268
269        let result = read_config_file(&config_path);
270        assert!(matches!(result, Err(OsedaCheckError::MissingConfig(_))));
271    }
272
273    #[test]
274    fn test_validate_config_success() {
275        let conf = OsedaConfig {
276            title: "my-project".to_string(),
277            author: "JaneDoe".to_string(),
278            tags: vec![Tag::ComputerScience],
279            last_updated: chrono::Utc::now(),
280            color: Color::Black.into_hex(),
281        };
282
283        let fake_dir = Path::new("/tmp/my-project");
284        // can mock the git credentials easier
285        let result = validate_config(&conf, fake_dir, false, || Some("JaneDoe".to_string()));
286
287        assert!(result.is_ok());
288    }
289
290    #[test]
291    fn test_validate_config_bad_git_user() {
292        let conf = OsedaConfig {
293            title: "my-project".to_string(),
294            author: "JaneDoe".to_string(),
295            tags: vec![Tag::ComputerScience],
296            last_updated: chrono::Utc::now(),
297            color: Color::Black.into_hex(),
298        };
299
300        let fake_dir = Path::new("/tmp/oseda");
301
302        let result = validate_config(&conf, fake_dir, false, || Some("NotJane".to_string()));
303
304        assert!(matches!(result, Err(OsedaCheckError::BadGitCredentials(_))));
305    }
306
307    #[test]
308    fn test_validate_config_bad_dir_name() {
309        let conf = OsedaConfig {
310            title: "correct-name".to_string(),
311            author: "JaneDoe".to_string(),
312            tags: vec![Tag::ComputerScience],
313            last_updated: chrono::Utc::now(),
314            color: Color::Black.into_hex(),
315        };
316
317        let fake_dir = Path::new("/tmp/wrong-name");
318
319        let result = validate_config(&conf, fake_dir, false, || Some("JaneDoe".to_string()));
320        assert!(matches!(
321            result,
322            Err(OsedaCheckError::DirectoryNameMismatch(_))
323        ));
324    }
325
326    #[test]
327    fn test_validate_config_skip_git() {
328        let conf = OsedaConfig {
329            title: "oseda".to_string(),
330            author: "JaneDoe".to_string(),
331            tags: vec![Tag::ComputerScience],
332            last_updated: chrono::Utc::now(),
333            color: Color::Black.into_hex(),
334        };
335
336        let fake_dir = Path::new("/tmp/oseda");
337
338        let result = validate_config(&conf, fake_dir, true, || None);
339        assert!(result.is_ok());
340    }
341}