aboutsummaryrefslogtreecommitdiff
path: root/crates/cli/src/exercises.rs
blob: 8cac7b0fcdb1a9886c58f2acb2df90888650ed9f (plain)
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
use inquire::{Confirm, Editor, Select, Text};
use mihi::exercise::{
    create_exercise, delete_exercise, find_exercise_by_title, select_by_title, update_exercise,
    Exercise, ExerciseKind,
};
use std::vec::IntoIter;

// Show the help message.
fn help(msg: Option<&str>) {
    if let Some(msg) = msg {
        println!("{}.\n", msg);
    }

    println!("mihi exercises: Manage exercises.\n");
    println!("usage: mihi exercises [OPTIONS] <subcommand>\n");

    println!("Options:");
    println!("   -h, --help\t\tPrint this message.");

    println!("\nSubcommands:");
    println!("   create\t\tCreate a new exercise.");
    println!("   edit\t\t\tEdit information from an exercise.");
    println!("   ls\t\t\tList exercises from the database.");
    println!("   rm\t\t\tRemove an exercises from the database.");
}

// Interactively ask the user to fill up an exercise based on the given
// `exercise` object.
fn ask_for_exercise_based_on(exercise: Exercise) -> Result<Exercise, String> {
    let Ok(title) = Text::new("Title:")
        .with_initial_value(&exercise.title)
        .prompt()
    else {
        return Err("abort!".to_string());
    };
    if title.trim().is_empty() {
        return Err("the title is required".to_string());
    }

    let Ok(enunciate) = Editor::new("Enunciate:")
        .with_predefined_text(&exercise.enunciate)
        .with_file_extension(".md")
        .prompt()
    else {
        return Err("abort!".to_string());
    };
    let enunciate = enunciate.trim().to_string();
    if enunciate.is_empty() {
        return Err("the enunciate is required".to_string());
    }

    let Ok(solution) = Editor::new("Solution:")
        .with_predefined_text(&exercise.solution)
        .with_file_extension(".md")
        .prompt()
    else {
        return Err("abort!".to_string());
    };
    let solution = solution.trim().to_string();
    if solution.trim().is_empty() {
        return Err("the solution is required".to_string());
    }

    let Ok(lessons) = Editor::new("Lessons:")
        .with_predefined_text(&exercise.lessons)
        .with_file_extension(".md")
        .prompt()
    else {
        return Err("abort!".to_string());
    };
    let lessons = lessons.trim().to_string();

    Ok(Exercise {
        id: exercise.id,
        title,
        enunciate,
        solution,
        lessons,
        kind: ExerciseKind::Simple,
    })
}

fn create(args: IntoIter<String>) -> i32 {
    if args.len() > 0 {
        help(Some(
            "error: exercises: no arguments were expected for this command",
        ));
        return 1;
    }

    let exercise = match ask_for_exercise_based_on(Exercise::default()) {
        Ok(ex) => ex,
        Err(e) => {
            println!("error: exercises: {e}");
            return 1;
        }
    };

    let title = exercise.title.clone();
    match create_exercise(exercise) {
        Ok(_) => {
            println!("Exercise '{title}' has been successfully created!");
            0
        }
        Err(e) => {
            println!("error: exercises: {e}");
            1
        }
    }
}

fn select_single_exercise(search: Option<String>) -> Result<Exercise, String> {
    let exercises = select_by_title(search)?;

    let title = match exercises.len() {
        0 => return Err("not found".to_string()),
        1 => exercises.first().unwrap().to_owned(),
        _ => match Select::new("Which exercise?", exercises)
            .with_page_size(20)
            .prompt()
        {
            Ok(choice) => choice,
            Err(_) => return Err("abort!".to_string()),
        },
    };

    find_exercise_by_title(title.as_str())
}

fn edit(mut args: IntoIter<String>) -> i32 {
    if args.len() > 1 {
        help(Some("error: exercises: too many filters"));
        return 1;
    }

    let exercise = match select_single_exercise(args.next()) {
        Ok(exercise) => exercise,
        Err(e) => {
            println!("error: exercises: {e}");
            return 1;
        }
    };

    let exercise = match ask_for_exercise_based_on(exercise) {
        Ok(ex) => ex,
        Err(e) => {
            println!("error: exercises: {e}");
            return 1;
        }
    };

    let title = exercise.title.clone();
    match update_exercise(exercise) {
        Ok(_) => {
            println!("Exercise '{title}' has been successfully updated!");
            0
        }
        Err(e) => {
            println!("error: exercises: {e}");
            1
        }
    }
}

fn ls(mut args: IntoIter<String>) -> i32 {
    if args.len() > 1 {
        help(Some("error: exercises: too many filters"));
        return 1;
    }

    let exercises = select_by_title(args.next()).unwrap_or(vec![]);
    for exe in exercises {
        println!("- '{}'", exe);
    }

    0
}

fn rm(mut args: IntoIter<String>) -> i32 {
    if args.len() > 1 {
        help(Some("error: exercises: too many filters"));
        return 1;
    }

    let exercise = match select_single_exercise(args.next()) {
        Ok(exercise) => exercise,
        Err(e) => {
            println!("error: words: {e}");
            return 1;
        }
    };
    let selection = exercise.title.as_str();

    let ans = Confirm::new(
        format!("Do you really want to remove '{selection}' from the database?",).as_str(),
    )
    .with_default(false)
    .prompt();

    match ans {
        Ok(true) => match delete_exercise(selection) {
            Ok(_) => println!("Removed '{selection}' from the database!"),
            Err(e) => {
                println!("error: words: {e}");
                return 1;
            }
        },
        Ok(false) => {
            println!("Doing nothing...");
        }
        Err(_) => return 1,
    }

    0
}

pub fn run(args: Vec<String>) {
    if args.is_empty() {
        help(Some(
            "error: exercises: you have to provide at least a subcommand",
        ));
        std::process::exit(1);
    }

    let mut it = args.into_iter();

    match it.next() {
        Some(first) => match first.as_str() {
            "-h" | "--help" => {
                help(None);
                std::process::exit(0);
            }
            "create" => {
                std::process::exit(create(it));
            }
            "edit" => {
                std::process::exit(edit(it));
            }
            "ls" => {
                std::process::exit(ls(it));
            }
            "rm" => {
                std::process::exit(rm(it));
            }
            _ => {
                help(Some(
                    format!("error: exercises: unknown flag or command '{first}'").as_str(),
                ));
                std::process::exit(1);
            }
        },
        None => {
            help(Some(
                "error: exercises: you need to provide a command"
                    .to_string()
                    .as_str(),
            ));
            std::process::exit(1);
        }
    }
}