oseda-cli 3.0.2

OSEDA project scaffolding
Documentation
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
use std::error::Error;
use std::fs::File;
use std::io::BufWriter;
use std::str::FromStr;
use std::{ffi::OsString, fs};

use chrono::{DateTime, Utc};
use inquire::validator::Validation;
use serde::{Deserialize, Serialize};
use strum::IntoEnumIterator;

use crate::cmd::check::OsedaCheckError;
use crate::cmd::init::InitOptions;
use crate::color::Color;
use crate::license::License;
use crate::tags::DefinedTag;
use crate::{github, license};

pub const CONFIG_FILE_NAME: &str = "oseda-config.json";

pub fn read_config_file<P: AsRef<std::path::Path>>(
    path: P,
) -> Result<OsedaConfig, OsedaCheckError> {
    let config_str = fs::read_to_string(path.as_ref()).map_err(|_| {
        OsedaCheckError::MissingConfig(format!(
            "Could not find config file in {}",
            path.as_ref().display()
        ))
    })?;

    let conf: OsedaConfig = serde_json::from_str(&config_str).map_err(|err| {
        OsedaCheckError::BadConfig(format!("Could not parse oseda config file: {}", err).to_owned())
    })?;

    Ok(conf)
}

/// Reads and validates an oseda-config.json file in the working directory
///
/// This checks a few things:
/// - the file exists and parses correctly
/// - the git `user.name` matches the config author (unless --skip-git is passed)
/// - the config `title` matches the name of the working directory
///
/// # Arguments
/// * `skip_git` - skips the git author validation, primarily used for CI, not by the end user hopefully lol
///
/// # Returns
/// * `Ok(OsedaConfig)` if the file is valid and all checks pass
/// * `Err(OsedaCheckError)` if any check fails
pub fn read_and_validate_config() -> Result<OsedaConfig, OsedaCheckError> {
    let path = std::env::current_dir().map_err(|_| {
        OsedaCheckError::DirectoryNameMismatch("Could not get path of working directory".to_owned())
    })?;

    let config_path = path.join(CONFIG_FILE_NAME);

    let conf = read_config_file(config_path)?;

    let in_ci = std::env::var("GITHUB_ACTIONS").is_ok_and(|v| v == "true");
    let skip_git = in_ci;

    validate_config(&conf, &path, skip_git, || {
        github::get_config_from_user_git("user.name")
    })?;

    Ok(conf)
}

pub fn validate_config(
    conf: &OsedaConfig,
    current_dir: &std::path::Path,
    skip_git: bool,
    // very cool pass in a lambda, swap that lambda out in the tests
    // https://danielbunte.medium.com/a-guide-to-testing-and-mocking-in-rust-a73d022b4075
    get_git_user: impl Fn() -> Option<String>,
) -> Result<(), OsedaCheckError> {
    if !skip_git {
        let gh_name = get_git_user().ok_or_else(|| {
            OsedaCheckError::BadGitCredentials(
                "Could not get git user.name from git config".to_owned(),
            )
        })?;

        if gh_name != conf.author {
            return Err(OsedaCheckError::BadGitCredentials(
                "Config author does not match git credentials".to_owned(),
            ));
        }
    }

    let cwd = current_dir.file_name().ok_or_else(|| {
        OsedaCheckError::DirectoryNameMismatch("Could not resolve path name".to_owned())
    })?;

    if cwd != OsString::from(conf.title.clone()) {
        return Err(OsedaCheckError::DirectoryNameMismatch(
            "Config title does not match directory name".to_owned(),
        ));
    }

    if conf.description.is_empty() || conf.description.eq_ignore_ascii_case(DEFAULT_DESCIPTION) {
        return Err(OsedaCheckError::MissingDescription(
            "Description is missing or empty. Please update the oseda-config.json".to_owned(),
        ));
    }

    if conf.tags.is_empty() {
        return Err(OsedaCheckError::MissingTags(
            "Please add tags to oseda-config.json".to_owned(),
        ));
    }

    Ok(())
}

/// Structure for an oseda-config.json
#[derive(Serialize, Deserialize)]
pub struct OsedaConfig {
    pub title: String,
    pub author: String,
    pub tags: Vec<String>,
    // effectively mutable. Will get updated on each deployment
    pub last_updated: DateTime<Utc>,
    pub color: String,
    // description must not be empty for check/deploy
    pub description: String,
    pub license: License,
}

const DEFAULT_DESCIPTION: &str = "Fill in project description";

pub fn prompt_for_title() -> Result<String, Box<dyn Error>> {
    let validator = |input: &str| {
        if input.chars().count() < 2 {
            Ok(Validation::Invalid(
                ("Title must be longer than two characters").into(),
            ))
        } else {
            Ok(Validation::Valid)
        }
    };

    Ok(inquire::Text::new("Title: ")
        .with_validator(validator)
        .prompt()?)
}
/// Prompts the user for everything needed to generate a new OsedaConfig
///
/// # Returns
/// * `Ok(OsedaConfig)` containing validated project config options
/// * `Err` if a required input conf is invalid
pub fn create_conf(options: InitOptions) -> Result<OsedaConfig, Box<dyn Error>> {
    let title = match options.title {
        Some(arg_title) => arg_title,
        None => prompt_for_title()?.replace(" ", "-"),
    };

    let defined_tags = match options.tags {
        Some(arg_tags) => {
            arg_tags
                .iter()
                .map(|arg_tag| DefinedTag::from_str(arg_tag.trim()))
                .collect::<Result<Vec<DefinedTag>, _>>()
                .map_err(|_| "Invalid tag. Custom Tags may be added to the oseda-config.json after initialization".to_string())?
        },
        None => prompt_for_tags()?
    };

    let color = match options.color {
        Some(arg_color) => Color::from_str(&arg_color)
            .map_err(|_| "Invalid color. Please use traditional english color names".to_string())?,
        None => prompt_for_color()?,
    };

    let user_name = github::get_config_from_user_git("user.name")
        .ok_or("Could not get GitHub username. Please ensure you are signed into github")?;

    let description = match options.description {
        Some(desc) => desc,
        None => DEFAULT_DESCIPTION.to_owned(),
    };

    let license = match options.license {
        Some(proposed_license) => License::try_from(proposed_license.clone()).or_else(|_| {
            eprintln!(
                "Error: Invalid license '{}', please select from the following:",
                proposed_license
            );
            prompt_for_license()
        })?,
        None => prompt_for_license()?,
    };

    Ok(OsedaConfig {
        title: title.trim().to_owned(),
        author: user_name,
        tags: defined_tags
            .into_iter()
            .map(|t: DefinedTag| DefinedTag::to_string(&t))
            .collect(),
        last_updated: get_time(),
        color: color.into_hex(),
        license,
        description,
    })
}

fn prompt_for_license() -> Result<License, Box<dyn Error>> {
    let options: Vec<String> = license::License::iter()
        .map(|lic: License| license::License::spdx_id(&lic))
        .map(|lic_str| lic_str.into())
        .collect();

    let selected_license =
        inquire::Select::new("Select license: (type to search):", options).prompt()?;

    Ok(License::try_from(selected_license)?)
}

/// Prompts user for categories associated with their Oseda project
///
/// # Returns
/// * `Ok(Vec<Category>)` with selected categories
/// * `Err` if the prompting went wrong somewhere
fn prompt_for_tags() -> Result<Vec<DefinedTag>, Box<dyn Error>> {
    let options: Vec<DefinedTag> = DefinedTag::iter().collect();

    let selected_tags =
        inquire::MultiSelect::new("Select categories (type to search):", options.clone())
            .prompt()?;

    println!("Selected Tags:");
    for tags in selected_tags.iter() {
        println!("- {:?}", tags);
    }

    Ok(selected_tags)
}

fn prompt_for_color() -> Result<Color, Box<dyn Error>> {
    let options: Vec<Color> = Color::iter().collect();

    let selected_color = inquire::Select::new(
        "Select the color for your course (type to search):",
        options.clone(),
    )
    .prompt()?;

    println!("Selected Color: {:?}", selected_color);

    Ok(selected_color)
}

/// Updates the configs last-updated
/// Currently this is used on creation only, TODO fix this
///
/// # Arguments
/// * `conf` - a previously loaded or generated OsedaConfig
///
/// # Returns
/// * `Ok(())` if the file is successfully updated
/// * `Err` if file writing fails
pub fn update_time(mut conf: OsedaConfig) -> Result<(), Box<dyn Error>> {
    conf.last_updated = get_time();

    write_config(".", &conf)?;
    Ok(())
}

/// Gets the current system time in UTC
///
/// # Returns
/// * a `DateTime<Utc>` representing the current time
fn get_time() -> DateTime<Utc> {
    chrono::offset::Utc::now()
}

/// Write an OsedaConfig to the provided directory
///
/// # Arguments
/// * `path` - the directory path to write into
/// * `conf` - the `OsedaConfig` instance to serialize via serde
///
/// # Returns            color: Color::Black
/// * `Ok(())` if the file is written successfully
/// * `Err` if file creation or serialization fails
pub fn write_config(path: &str, conf: &OsedaConfig) -> Result<(), Box<dyn Error>> {
    let file = File::create(format!("{}/oseda-config.json", path))?;
    let writer = BufWriter::new(file);

    serde_json::to_writer_pretty(writer, &conf)?;

    Ok(())
}

#[cfg(test)]
mod test {
    use crate::tags::DefinedTag;
    use std::path::Path;
    use tempfile::tempdir;

    use super::*;

    #[allow(dead_code)]
    fn mock_config_json() -> String {
        r#"
           {
               "title": "TestableRust",
               "author": "JaneDoe",
               "category": ["ComputerScience"],
               "last_updated": "2024-07-10T12:34:56Z"
           }
           "#
        .trim()
        .to_string()
    }

    #[test]
    fn test_read_config_file_missing() {
        let dir = tempdir().unwrap();
        let config_path = dir.path().join("oseda-config.json");

        let result = read_config_file(&config_path);
        assert!(matches!(result, Err(OsedaCheckError::MissingConfig(_))));
    }

    #[test]
    fn test_validate_config_success() {
        let conf = OsedaConfig {
            title: "my-project".to_string(),
            author: "JaneDoe".to_string(),
            tags: vec![DefinedTag::ComputerScience.to_string()],
            last_updated: chrono::Utc::now(),
            license: License::Apache2_0,
            color: Color::Black.into_hex(),
            description: String::from("Test Description"),
        };

        let fake_dir = Path::new("/tmp/my-project");
        // can mock the git credentials easier
        let result = validate_config(&conf, fake_dir, false, || Some("JaneDoe".to_string()));

        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_config_bad_git_user() {
        let conf = OsedaConfig {
            title: "my-project".to_string(),
            author: "JaneDoe".to_string(),
            tags: vec![DefinedTag::ComputerScience.to_string()],
            last_updated: chrono::Utc::now(),
            license: License::Mit,
            color: Color::Black.into_hex(),
            description: String::from("Test Description"),
        };

        let fake_dir = Path::new("/tmp/oseda");

        let result = validate_config(&conf, fake_dir, false, || Some("NotJane".to_string()));

        assert!(matches!(result, Err(OsedaCheckError::BadGitCredentials(_))));
    }

    #[test]
    fn test_validate_config_bad_dir_name() {
        let conf = OsedaConfig {
            title: "correct-name".to_string(),
            author: "JaneDoe".to_string(),
            tags: vec![DefinedTag::ComputerScience.to_string()],
            last_updated: chrono::Utc::now(),
            license: License::Bsd3Clause,
            color: Color::Black.into_hex(),
            description: String::new(),
        };

        let fake_dir = Path::new("/tmp/wrong-name");

        let result = validate_config(&conf, fake_dir, false, || Some("JaneDoe".to_string()));
        assert!(matches!(
            result,
            Err(OsedaCheckError::DirectoryNameMismatch(_))
        ));
    }

    #[test]
    fn test_validate_config_skip_git() {
        let conf = OsedaConfig {
            title: "oseda".to_string(),
            author: "JaneDoe".to_string(),
            tags: vec![DefinedTag::ComputerScience.to_string()],
            last_updated: chrono::Utc::now(),
            color: Color::Black.into_hex(),
            license: License::Gpl3_0,
            description: String::from("Test Description"),
        };

        let fake_dir = Path::new("/tmp/oseda");

        let result = validate_config(&conf, fake_dir, true, || None);
        assert!(result.is_ok());
    }
}