-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.rs
More file actions
278 lines (243 loc) · 8.15 KB
/
main.rs
File metadata and controls
278 lines (243 loc) · 8.15 KB
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
use serde::{Serialize, Deserialize}; //convert from string to object and vice-versa
use std::io;
use std::fs;
use chrono::Local; //note timestamps
use colored::*;
use inquire::Select; //interactive menu
use clap::{Parser, Subcommand}; //CLI functionality
//store notes universally
use std::path::PathBuf;
use directories::ProjectDirs;
//find/create notes folder and json file
fn get_database_path() -> PathBuf {
if let Some(proj_dirs) = ProjectDirs::from("", "", "notes") {
let data_dir = proj_dirs.data_dir();
if !data_dir.exists() {
let _ = fs::create_dir_all(data_dir);
}
return data_dir.join("notes.json");
}
//creates locally if no home directory
PathBuf::from("notes.json")
}
fn print_banner() {
println!("{}", "
███╗ ██╗ ██████╗ ████████╗███████╗███████╗
████╗ ██║██╔═══██╗╚══██╔══╝██╔════╝██╔════╝
██╔██╗ ██║██║ ██║ ██║ █████╗ ███████╗
██║╚██╗██║██║ ██║ ██║ ██╔══╝ ╚════██║
██║ ╚████║╚██████╔╝ ██║ ███████╗███████║
╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚══════╝╚══════╝"
.truecolor(14, 184, 219).bold());
}
#[derive(Serialize, Deserialize, Debug)]
struct Note {
id: u32,
body: String,
timestamp: String,
}
//CLAP Init
#[derive(Parser)]
#[command(name = "notes")]
#[command(about = "CLI Note Application", long_about = None)]
struct Cli {
#[command(subcommand)]
//if none, trigger interactive version (handled in main)
command: Option<Commands>,
}
//define commands
#[derive(Subcommand)]
enum Commands {
/// add note
#[command(visible_alias = "a")]
Add {
note: String
},
/// remove note by id
#[command(visible_aliases = ["rm", "del"])]
Remove {
id: u32
},
/// view all notes
#[command(visible_aliases = ["view", "ls"])]
List,
/// show data location
#[command(visible_aliases = ["location", "where"])]
Path,
}
fn add_note(notes: &mut Vec<Note>) -> io::Result<()> {
let body: String = loop {
println!("Enter note ('q' to cancel): ");
let mut input = String::new();
io::stdin().read_line(&mut input)?;
//cancel
if input.trim().eq_ignore_ascii_case("q") {
println!(">Cancelled");
return Ok(());
}
//empty note
if input.trim().is_empty() {
println!("{}", "Error: Note cannot be empty".red().bold());
continue; //restart loop
}
break input.trim().to_string();
};
let now = Local::now();
let now_formatted = now.format("%Y-%m-%d %H:%M:%S").to_string();
let new_note = Note {
id: notes.len() as u32 + 1,
body: body,
timestamp: now_formatted,
};
notes.push(new_note);
println!("{}", ">Note added".green().bold());
Ok(())
}
fn remove_note(notes: &mut Vec<Note>) -> io::Result<()> {
loop {
println!("Enter note ID to remove ('q' to cancel): ");
let mut input = String::new();
io::stdin().read_line(&mut input)?;
//cancel
if input.trim().eq_ignore_ascii_case("q") {
println!(">Cancelled");
break;
}
let id: u32 = match input.trim().parse() {
Ok(num) => num,
Err(_) => {
println!("{}", "Error: Enter a valid number".red().bold());
continue; //restart loop
}
};
//check bounds
if id == 0 || id > notes.len() as u32 {
println!("{}", format!("Error: Note {} does not exist", id).red().bold());
continue; //restart loop
}
let index = (id - 1) as usize;
notes.remove(index);
println!("{}", format!(">Removed Note {}", id).green().bold());
//update indices
for (i, note) in notes.iter_mut().enumerate() {
note.id = (i+1) as u32;
}
break;
}
Ok(())
}
fn save_notes(notes: &Vec<Note>) {
let db_path = get_database_path();
if let Ok(json) = serde_json::to_string_pretty(notes) {
let _ = fs::write(db_path, json);
}
}
fn load_notes() -> Vec<Note> {
let db_path = get_database_path();
if let Ok(data) = fs::read_to_string(db_path) {
serde_json::from_str(&data).unwrap_or_default()
} else {
Vec::new()
}
}
fn main() -> io::Result<()> {
// CLI arguments
let cli = Cli::parse();
let mut notes: Vec<Note> = load_notes();
if let Some(cmd) = cli.command {
match cmd {
Commands::Add { note } => {
// copy add_note logic without loop
let now = Local::now().format("%Y-%m-%d %H:%M:%S").to_string();
let new_note = Note {
id: notes.len() as u32 + 1,
body: note,
timestamp: now,
};
notes.push(new_note);
save_notes(¬es);
println!("{}", "> Note added".green().bold());
}
Commands::Remove { id} => {
if id == 0 || id > notes.len() as u32 {
eprintln!("{}", format!("Error: Note {} does not exist", id).red().bold());
} else {
let index = (id - 1) as usize;
notes.remove(index);
//update indices
for (i, note) in notes.iter_mut().enumerate() {
note.id = (i+1) as u32;
}
save_notes(¬es);
println!("{}", format!(">Removed Note {}", id).green().bold());
}
}
Commands::List => {
if notes.is_empty() {
println!("{}", "No notes found".yellow().bold());
} else {
println!("\n------NOTES------");
for note in ¬es {
println!("{}. {} ({})", note.id, note.body, note.timestamp);
}
println!("-----------------\n");
}
}
Commands::Path => {
println!("{}", get_database_path().display());
}
}
return Ok(());
}
// --- Interactive Loop --- //
print_banner();
loop {
let options = vec![
"Add Note",
"Remove Note",
"View Notes",
"Quit",
];
let choice = Select::new("", options).prompt();
match choice {
Ok("Add Note") => {
if let Err(e) = add_note(&mut notes) {
eprint!("{} {}", "Error adding note:".red().bold(), e);
} else {
save_notes(¬es);
println!();
}
},
Ok("Remove Note") => {
if let Err(e) = remove_note(&mut notes) {
eprint!("{} {}", "Error removing note:".red().bold(), e);
} else {
save_notes(¬es);
println!();
}
},
Ok("View Notes") => {
if notes.is_empty() {
println!("{}", "No notes found".yellow().bold());
continue;
} else {
println!("------NOTES------");
for note in ¬es {
println!("{}. {} ({})", note.id, note.body, note.timestamp);
}
println!("-----------------\n");
}
},
Ok("Quit") => {
println!();
println!("{}", ">Quitting...".yellow().bold());
break;
},
Err(_) => {
println!("{}", "Error: Invalid choice".red().bold());
},
_ => {}
}
}
Ok(())
}